import os
import shutil
from PIL import Image, ImageStat
from statistics import median
import numpy as np

def calculate_brightness(image_path):
    img = Image.open(image_path)
    stat = ImageStat.Stat(img)
    brightness = sum(stat.mean) / 3
    return brightness

def find_underexposed_images(folder_path, z_exposure_path, brightness_threshold):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            if file.endswith('.jpg') or file.endswith('.jpeg') or file.endswith('.png'):
                brightness = calculate_brightness(file_path)
                if brightness < brightness_threshold:
                    source_folder = os.path.dirname(file_path)
                    target_folder = os.path.join(z_exposure_path, source_folder.split(os.sep)[-1])
                    if not os.path.exists(target_folder):
                        os.makedirs(target_folder)
                    target_file_path = os.path.join(target_folder, file)
                    shutil.move(file_path, target_file_path)
                    print(f"Moved {file_path} to {target_folder}")

def determine_brightness_threshold(sample_folder, percentile=10):
    brightnesses = []
    for root, dirs, files in os.walk(sample_folder):
        for file in files:
            file_path = os.path.join(root, file)
            if file.endswith('.jpg') or file.endswith('.jpeg') or file.endswith('.png'):
                brightness = calculate_brightness(file_path)
                brightnesses.append(brightness)
                # print(f"Image: {file_path}, Brightness: {brightness}")
    
    # 计算亮度分布的百分位数作为阈值
    brightness_threshold = np.percentile(brightnesses, percentile)
    print(f"Initial threshold: {brightness_threshold}")
    
    return brightness_threshold

# 设置要查找的文件夹路径
folder_path = 'img_not_same'

# 设置要移动的图片的文件夹路径
z_exposure_path = 'z_underexposure'

# 设置包含样本图片的文件夹路径
sample_folder = 'underexposure_samples'

# 确定亮度阈值
brightness_threshold = determine_brightness_threshold(sample_folder)

# 根据阈值查找并移动大部分区域都是过黑的图片
find_underexposed_images(folder_path, z_exposure_path, brightness_threshold)